package com.maomao.SMSUtil;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author xiaomin
 * @date 2018/4/13
 */
public class HttpClientUtil {

    /**
     * post发送json数据
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, JSONObject param) {
        HttpPost httpPost = null;
        String result = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            if (param != null) {
                StringEntity se = new StringEntity(param.toString(), "utf-8");
                httpPost.setEntity(se); // post方法中，加入json数据
                httpPost.setHeader("Content-Type", "application/json");
            }

            HttpResponse response = httpclient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String url = "http://www.yescloudtree.cn:28009";
        Map<String, Object> map = new HashMap<>();
        map.put("Action","sendsms");
        map.put("UserName","hzjbyzm");
        map.put("Password","1A66860A2857ADE7793D38A9D267A118");
        map.put("Mobile","18720971965");
        map.put("Message","5oKo55qE6aqM6K+B56CB77yaMTIzNDU2");
        JSONObject param = (JSONObject) JSONObject.toJSON(map);

       System.out.println(doPost(url,param));
    }

}
